<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Task;
use App\Services\Home\CategoryService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use MongoDB\BSON\ObjectId;

class HomeController extends Controller
{
    protected $request;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 获取首页左侧导航
     * @param CategoryService $categoryService
     * @return \Illuminate\Http\JsonResponse
     */
    public function categories(CategoryService $categoryService)
    {
        $result = $categoryService->getCategories();
        return $result;
    }

    public function upload(Request $request)
    {
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $file_name = md5(env('app_key') . time()) . '.' . $file->getClientOriginalExtension();
            $store_path = 'images/' . date('Y-m');

            // 自动生成一个唯一文件名
            $path = Storage::putFile($store_path, $file);
            if (!file_exists($store_path)) {
                mkdir($store_path, 0777, true);
            }
            if ($file->move($store_path, $file_name)) {
                return uploadSuccess('上传成功！', Storage::url($path));
            } else {
                return Error('上传失败！');
            }
        } else {
            return uploadSuccess('请选择文件！', $request->all());
        }

    }

    /**
     * 接收服务端返回的产品数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_task_data(Request $request)
    {
        $params = $request->post();

        //更新任务为已完成
        Task::where('_id', new ObjectId($params['client_task_id']))->update(['get_product_status' => 'completed']);

        //插入本地产品表
        Product::insert($params['product_info']);

        return Success('ok',$params);
    }
}
